package util;
import javax.swing.text.*;  
      
public class FixedLengthDocument extends PlainDocument { 
	
	private static final long serialVersionUID = 1L;
	private int maxLength;  
	private boolean apenasNumeros;
   
    public FixedLengthDocument(int maxlen, boolean apenasNumeros) {  
        super();  
        this.maxLength = maxlen; 
        this.apenasNumeros = apenasNumeros;
    }  
  
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { 
    	
    	if(apenasNumeros) {
    		for (int i = 0; i < str.length(); i++) {
    			if(!Character.isDigit(str.charAt(i)))
    				return;
    		}
    	}
    	
        if (str == null)
        	return;  
  
        if(maxLength <= 0) {  
            super.insertString(offset, str, attr);  
            return;  
        }  
  
        int ilen = (getLength() + str.length());
        
        if (ilen <= maxLength) {     
            super.insertString(offset, str, attr);
            
        } else if(getLength() == maxLength) { 
        	return;
        	
        } else {
        	String newStr = str.substring(0,(maxLength - getLength()));   
            super.insertString(offset, newStr, attr);  	
        }
    }  
}  